package com.unitd.sso;

import com.unitd.frame.sso.common.helper.SSOHelper;
import com.unitd.frame.sso.common.token.SSOToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @desc SSO支持SpringBoot演示控制器
 * @filename LoginController.java
 * @copyright www.unitd.com
 * @author Hudan
 * @version 1.0
 * @date 2018/1/10
 */
@Controller
public class LoginController {

	@Autowired
	protected HttpServletRequest request;
	@Autowired
	protected HttpServletResponse response;

	@ResponseBody
	@RequestMapping("/")
	public String home() {
		return "Hello sso!";
	}

	// 授权登录
	@ResponseBody
	@RequestMapping("/login")
	public String login() {
		// 设置登录 COOKIE
		SSOHelper.setSSOCookie(request, response, new SSOToken(request), false);
		return "login success!";
	}

	// 查看登录信息
	@ResponseBody
	@RequestMapping("/token")
	public String token() {
		String msg = "暂未登录";
		SSOToken ssoToken = SSOHelper.attrToken(request);
		if (null != ssoToken) {
			msg = "登录信息 ip=" + ssoToken.getIp();
			msg += "， id=" + ssoToken.getId();
			msg += "， issuer=" + ssoToken.jsonToken();
		}
		return msg;
	}

	// 退出登录
	@ResponseBody
	@RequestMapping("/logout")
	public String logout() {
		SSOHelper.clearLogin(request, response);
		return "Logout sso!";
	}
}